<template>
    <el-card class="w-full pt-[5px]">
        <el-radio-group v-model="planType" @change="getList(1)">
            <el-radio-button v-for="item in statisticsList" :key="item.value" :value="item.value">{{ item.name }}({{
            item.count
        }})</el-radio-button>
        </el-radio-group>
        <el-form :model="searchForm" class="mt-[20px]" label-width="110px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="成果名称" class="mb-[0px]">
                        <el-input v-model="searchForm.name" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="鉴定部门" class="mb-[0px]">
                        <el-input v-model="searchForm.appraisalUnit" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="鉴定结论">
                        <CustomTreeSelect placeholder="鉴定结论" v-model="searchForm.appraisalResultIdList" valueKey="code"
                            labelKey="name" :isFetch="false" :dataList="jdjgList" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <div class="flex justify-end">
                        <el-button type="primary" @click="searchFormOpen = !searchFormOpen">更多
                            <el-icon color="#fff">
                                <CaretTop v-show="searchFormOpen" />
                                <CaretBottom v-show="!searchFormOpen" />
                            </el-icon>
                        </el-button>
                        <el-button type="primary" @click="queryMet">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mt-[0px]" v-show="searchFormOpen">
                <el-col :span="6">
                    <el-form-item label="参与作者" class="mb-[0px]">
                        <el-input v-model="searchForm.authorName" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="鉴定日期" class="mb-[0px]">
                        <!-- <el-date-picker v-model="valueDate1" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                            type="daterange" range-separator="至" /> -->
                        <CommonDateSelect placeholder="鉴定日期" v-model:beginTime="searchForm.appraisalDateStart"
                            v-model:endTime="searchForm.appraisalDateEnd" v-model:dateformat="searchForm.dateFormat" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="所属单位">
                        <CustomTreeSelect placeholder="所属单位" v-model="searchForm.unitIdList" valueKey="codeColumn"
                            labelKey="valueColumn" :isFetch="false" :dataList="zcgsdwList" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="鉴定号" class="mb-[0px]">
                        <el-input v-model="searchForm.appraisalCode" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="完成形式">
                        <el-select v-model="searchForm.completeTypeId" clearable>
                            <el-option v-for="item in wcxsList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="学校署名">
                        <el-select v-model="searchForm.schoolSign" clearable>
                            <el-option label="第一单位" value="0" />
                            <el-option label="非第一单位" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="完成单位" class="mb-[0px]">
                        <el-input v-model="searchForm.completeUnits" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="审核状态">
                        <CustomTreeSelect placeholder="审核状态" v-model="searchForm.checkstatusList" valueKey="code"
                            labelKey="name" :isFetch="false" :dataList="shztList" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
    <el-card class="w-full pt-[5px] mt-[10px]">
        <div class="mb-[20px]">
            <el-button type="primary" v-equalRole="['biz_kyry', 'biz_kycgly']" @click="handleAdd">
                <el-icon class="mr-[5px]">
                    <Plus />
                </el-icon>
                新增
            </el-button>
            <el-button @click="handleDel">
                <el-icon>
                    <DeleteFilled />
                </el-icon>
                删除
            </el-button>
            <el-button v-equalRole="['biz_kycgly', 'biz_kyms']" @click="exportVisible = true">
                <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
            </el-button>
        </div>
        <el-table :data="tableData" class="w-full" @selection-change="handleSelectionChange" stripe>
            <el-table-column type="selection" width="55" :selectable="checkSelectable" />
            <el-table-column prop="name" label="成果名称">
                <template #default="scope">
                    <el-link type="primary" @click="viewItem(scope.row)">{{ scope.row.name }}</el-link>
                </template>
            </el-table-column>
            <el-table-column prop="appraisalUnit" label="鉴定部门" />
            <el-table-column prop="appraisalResultId" label="鉴定结论">
                <template #default="scope">
                    <Feedback :id="scope.row.appraisalResultId" :list="jdjgList">
                    </Feedback>
                </template>
            </el-table-column>
            <el-table-column prop="inventorNames" label="所有完成人">
                <template #default="scope">
                    <span v-for="(item, index) in scope.row.authorList1" :key="item.id">
                        <el-link type="primary" v-if="item.id != '3'" @click="openpeopledetails(item)">{{
            item.name
        }}<span v-if="index + 1 != scope.row.authorList1.length">,</span></el-link>
                        <span type="primary" v-else>{{
            item.name
        }}<span v-if="index + 1 != scope.row.authorList1.length">,</span></span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="appraisalDate" label="鉴定日期" />
            <el-table-column prop="unitId" label="所属单位">
                <template #default="scope">
                    <Feedback :id="scope.row.unitId" :list="zcgsdwList" :mapping="['codeColumn', 'valueColumn']">
                    </Feedback>
                </template>
            </el-table-column>
            <el-table-column prop="checkstatus" label="审核状态"> <template #default="scope">
                    <Feedback :id="scope.row.checkstatus" :list="shztList">
                    </Feedback>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="300" align="center">
                <template #default="scope">
                    <el-button type="primary" size="small" plain
                        v-show="editRole(scope.row.checkstatus, scope.row.authorList1)" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="success" v-show="scope.row.isAuditor" v-equalRole="['biz_kycgly', 'biz_kyms']"
                        size="small" @click="handleCheck(scope.row.id, scope.row.processInstanceId)" plain>
                        审核
                    </el-button>
                    <el-button type="warning" size="small" v-equalRole="['biz_kyry']" plain
                        @click="handleCancel(scope.row)" :loading="scope.row.processLoading"
                        v-show="scope.row.checkstatus == '1' && scope.row.authorList1[0].id == userRealId">撤销</el-button>
                    <el-button v-show="(scope.row.checkstatus == '-1' || scope.row.checkstatus == '3') &&
            scope.row.authorList1[0].id == userRealId && checkSelectable(scope.row)" type="danger" size="small"
                        v-equalRole="['biz_kyry']" plain @click="delHonor(scope.row)">删除</el-button>
                    <el-button
                        v-show="(scope.row.checkstatus == '-1' || scope.row.checkstatus == '3') && checkSelectable(scope.row)"
                        type="danger" size="small" v-equalRole="['biz_kyms']" plain
                        @click="delHonor(scope.row)">删除</el-button>
                    <el-button type="danger" size="small" v-show="checkSelectable(scope.row)"
                        v-equalRole="['biz_kycgly']" plain @click="delHonor(scope.row)">删除</el-button>

                </template>
            </el-table-column>
        </el-table>
        <div class="mt-[20px] flex justify-end">
            <pagination v-show="total > 0" :total="total" v-model:page="pageInfo.pageNum"
                v-model:limit="pageInfo.pageSize" @pagination="getList" />
        </div>
    </el-card>
    <EditModal v-model="editModelVisible" ref="EditModalRef" :xlList="xlList" :zcList="zcList" :zcgsdwList="zcgsdwList"
        :jdjgList="jdjgList" :wcxsList="wcxsList" :sydwList="sydwList" @callBack="callBackFun">
    </EditModal>
    <viewModal v-model="ViewdialogVisible" ref="viewModalRef" :xlList="xlList" :zcList="zcList" :zcgsdwList="zcgsdwList"
        :jdjgList="jdjgList" :wcxsList="wcxsList" :sydwList="sydwList" />
    <exportModal v-model="exportVisible" :selectList="exportList" title="成果评价" @callBack="callBackMet" />
    <CheckModal v-model="CheckModalVisible" ref="checkModalRef" :xlList="xlList" :zcList="zcList"
        :zcgsdwList="zcgsdwList" :sydwList="sydwList" :jdjgList="jdjgList" :wcxsList="wcxsList"
        @callBack="callBackFun" />
    <peopleDetails :activ="activ" :obj="obj" @close-dialog="activ = false"></peopleDetails>
</template>

<script setup>
import { onMounted } from 'vue';
import { getCategory } from "@/api/system/category"
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
    getappraisalList, appraisalDel, getappraisalInfo,
    getappraisalListStatistics
} from "@/api/achievement/kycg"
import EditModal from "./EditModal.vue";
import viewModal from "./viewModal.vue";
import useCategoryStore from "@/store/modules/category";
import CommonDateSelect from "@/views/achievement/components/CommonDateSelect";
import exportModal from "@/components/export";
import { exportFile } from "@/api/fee/common.js";
import { downloadFile } from "@/utils/main";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import Cookies from 'js-cookie'
import CheckModal from "./CheckModal.vue";
import { cancelProcess } from "@/api/project/common";
import peopleDetails from '@/components/peopleDetails/peopleDetails.vue'
import useUserStore from "@/store/modules/user";

const categoryStore = useCategoryStore();
const { shztList, zcgsdwList, jdjgList, xlList, zcList, wcxsList,
    sydwList } = storeToRefs(categoryStore); // 解构状态
const { getshztList, getzcgsdwList, getjdjgList, getxlList, getzcList, getwcxsList,
    getsydwList } = categoryStore; // 解构方法

const router = useRouter();
const planType = ref("");
const searchFormOpen = ref(false);
const editModelVisible = ref(false);
const viewSbModalVisible = ref(false);
const exportVisible = ref(false);
const CheckModalVisible = ref(false);


const searchForm = ref({
    name: '',
    appraisalUnit: '',
    appraisalResultIdList: [],
    authorName: '',
    appraisalCode: "",
    completeTypeId: "",
    schoolSign: "",
    completeUnits: "",
    unitIdList: [],
    checkstatusList: [],
    appraisalDateStart: '',
    appraisalDateEnd: '',
    dateFormat: 'yyyy-MM-dd',

});
const pageInfo = ref({
    pageNum: 1,
    pageSize: 10
})

const total = ref(0)
const tableData = ref([]);
//点击新增
const handleAdd = () => {
    editModelVisible.value = true;
    EditModalRef.value.getKyryInfo();
};

const EditModalRef = ref(null)
//点击编辑
const handleEdit = (i) => {
    getappraisalInfo(i.id).then(res => {
        console.log(res)
        if (res.code == 200) {
            editModelVisible.value = true;
            EditModalRef.value.getFrom(res.data)

        }
    })

};
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
//点击删除
const handleDel = () => {
    if (multipleSelection.value.length == 0) {
        ElMessage.warning("请选择要删除的数据")
        return;

    } else {
        ElMessageBox.confirm("是否确认删除？", "提示", {
            type: "warning",
        }).then(() => {
            let ids = multipleSelection.value.map(item => item.id)
            ids = ids.join(',')
            appraisalDel(ids).then(res => {
                if (res.code == 200) {
                    getList()
                    ElMessage.success('删除成功')
                }
            })
        });
    }

};
const initList = () => {
    getList()
}
const valueDate1 = ref('')
const reset = () => {
    valueDate1.value = ''
    searchForm.value = {
        name: '',
        appraisalUnit: '',
        appraisalResultIdList: [],
        authorName: '',
        appraisalCode: "",
        completeTypeId: "",
        schoolSign: "",
        completeUnits: "",
        unitIdList: [],
        checkstatusList: [],
        appraisalDateStart: '',
        appraisalDateEnd: '',
        dateFormat: 'yyyy-MM-dd',
    }
}
/**
 * 获取专利列表数据
 *
 * @returns 无返回值
 */
const getList = async (i) => {
    getListStatisticsMet()
    if (i == 1) {
        pageInfo.value.pageNum = 1
    }
    let parms = {
        ...searchForm.value,
        ...pageInfo.value,
        checkstatus: planType.value,
    }
    let res = await getappraisalList(parms)
    if (res.code == 200) {
        tableData.value = res.rows
        tableData.value.forEach(item => {
            if (item.authornames && item.authorpids) {
                let zcNameArr = item.authornames.split(',')
                let zcNameArr1 = item.authorpids.split(',')
                let zcNameArr2 = zcNameArr.map((val, index) => {
                    return {
                        name: val,
                        id: zcNameArr1[index]
                    }
                })
                console.log(zcNameArr2)
                Reflect.set(item, 'authorList1', zcNameArr2)
            }
            Reflect.set(item, "processLoading", false);
        })
        total.value = res.total

    }

}
const callBackFun = () => {
    getList()
}
const delHonor = (i) => {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            appraisalDel(i.id).then(res => {
                if (res.code == 200) {
                    getList()
                    ElMessage.success('删除成功')
                }
            })


        })
        .catch(() => {

        })

}

const ViewdialogVisible = ref(false);
const viewModalRef = ref(null);

const viewItem = (i) => {
    getappraisalInfo(i.id).then((res) => {
        if (res.code == 200) {
            ViewdialogVisible.value = true;
            viewModalRef.value.getRuleForm(res.data)
        }
    })
};
const exportList = [{
    lable: '成果名称',
    value: 'name',
    isSelect: true,
}, {
    lable: '鉴定号',
    value: 'appraisalCode',
    isSelect: true,
}, {
    lable: '鉴定部门',
    value: 'appraisalUnit',
    isSelect: true,
}, {
    lable: '鉴定日期',
    value: 'appraisalDate',
    isSelect: true,
}, {
    lable: '鉴定结论',
    value: 'appraisalResultId',
    isSelect: true,
}, {
    lable: '完成形式',
    value: 'completeTypeId',
    isSelect: false,
}, {
    lable: '所属单位',
    value: 'unitId',
    isSelect: true,
}, {
    lable: '所有完成人',
    value: 'authornames',
    isSelect: true,
}, {
    lable: '学校署名',
    value: 'schoolSign',
    isSelect: false,
}, {
    lable: '完成单位',
    value: 'completeUnits',
    isSelect: false,
}, {
    lable: '审核状态',
    value: 'checkstatus',
    isSelect: false,
}]

const callBackMet = (i) => {
    let parms = {
        excelColumn: i.map(item => item.prop),
        ...searchForm.value,
        checkstatus: planType.value,
    }
    exportFile('​/achievement​/appraisal/export', parms).then(res => {
        downloadFile(res, `成果评价清单_${new Date().getTime()}.xlsx`);
    })
}

const editRole = (i, j) => {
    if (Cookies.get("role-key") == 'biz_kyry') {
        if ((i == '-1' || i == '3') && j[0].id == userRealId.value) {
            return true;
        } else {
            return false;
        }
    } else if (Cookies.get("role-key") == 'biz_kyms') {
        if (i == '-1' || i == '3' || i == '1') {
            return true;
        } else {
            return false;
        }
    } else if (Cookies.get("role-key") == 'biz_kycgly') {
        return true;
    } else {
        return false;
    }

}

const checkModalRef = ref();
//点击审核
const handleCheck = (id, processId) => {
    getappraisalInfo(id).then((res) => {
        if (res.code == 200) {
            CheckModalVisible.value = true;
            checkModalRef.value.getRuleForm(res.data, processId);
        }
    });
};
// const processLoading = ref(false);
//点击撤销
const handleCancel = async (i) => {
    try {
        i.processLoading = true;
        const res = await cancelProcess(i.processInstanceId);
        if (res.data) {
            ElMessage({
                message: "操作成功！",
                type: "success",
            });
            initList();
        } else {
            ElMessage({
                message: "操作失败！",
                type: "warning",
            });
        }
        i.processLoading = false;
    } catch (error) {
        console.log(error);
        i.processLoading = false;
    }
};

const statisticsList = ref([{
    name: "全部",
    value: '',
    count: 0
},
{
    name: "审批通过",
    value: '2',
    count: 0
},
{
    name: "审批不通过",
    value: '3',
    count: 0
},
{
    name: "审批中",
    value: '1',
    count: 0
}])

const getListStatisticsMet = async () => {
    let parms = {
        ...searchForm.value,
    };
    let res = await getappraisalListStatistics(parms);
    if (res.code == 200) {
        statisticsList.value.forEach(item => {
            if (item.name != '全部') {
                let hasStatis = res.data.filter(item1 => {
                    return item1.checkSatus == item.value
                })
                hasStatis && hasStatis.length ? item.count = hasStatis[0].count : item.count = 0
            }


        })
        let allNum = 0
        res.data.forEach(item => {
            allNum += item.count
        })
        statisticsList.value[0].count = allNum
    }
}
const queryMet = () => {
    getList(1)
}

///查看详情
const activ = ref(false)
const obj = ref('')
const openpeopledetails = function (row) {
    obj.value = row.id
    activ.value = true
}



const checkSelectable = (row, index) => {
    return row.checkstatus != '1';
}


const userStore = useUserStore();

const userRealId = ref('')



onMounted(() => {
    if (!shztList.value.length) {
        getshztList()
    }
    if (!zcgsdwList.value.length) {
        getzcgsdwList()
    }
    if (!jdjgList.value.length) {
        getjdjgList()
    }
    if (!xlList.value.length) {
        getxlList()
    }
    if (!zcList.value.length) {
        getzcList()
    }
    if (!wcxsList.value.length) {
        getwcxsList()
    }
    if (!sydwList.value.length) {
        getsydwList();
    }


    userRealId.value = userStore.userRealId
    initList()
})

</script>